package com.tianma315.admin.staff.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tianma315.admin.common.base.CoreServiceImpl;
import com.tianma315.admin.common.exception.MessageException;
import com.tianma315.admin.device.domain.DeviceDO;
import com.tianma315.admin.device.domain.DeviceTypeDO;
import com.tianma315.admin.marshalling.domain.MarshallingDO;
import com.tianma315.admin.marshalling.service.MarshallingService;
import com.tianma315.admin.staff.VO.StaffVO;
import com.tianma315.admin.supplier.domain.SupplierTypeDO;
import com.tianma315.admin.sys.domain.DeptDO;
import com.tianma315.admin.sys.service.DeptService;
import com.tianma315.admin.util.CellUtil;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tianma315.admin.staff.dao.StaffDao;
import com.tianma315.admin.staff.domain.StaffDO;
import com.tianma315.admin.staff.service.StaffService;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.sql.Wrapper;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 
 * <pre>
 * 员工表
 * </pre>
 * <small> 2019-05-27 15:30:33 | Aron</small>
 */
@Service
public class StaffServiceImpl extends CoreServiceImpl<StaffDao, StaffDO> implements StaffService {
    @Autowired
    private StaffDao staffDao;

    @Autowired
    private MarshallingService marshallingService;

    @Autowired
    private DeptService deptService;

    @Override
    public Page<StaffVO> getStaffVOPage(Integer pageNumber, Integer pageSize, StaffDO staffDTO) {
        Page<StaffVO> page = new Page<>(pageNumber,pageSize);
        List<StaffVO> staffVOList = staffDao.getStaffVOPage(page,staffDTO);
        page.setRecords(staffVOList);
//        page.setTotal(staffVOList.size());
        return page;
    }

    @Override
    public StaffVO getStaffVO(Integer id) {
        StaffDO staffDTO = new StaffDO();
        staffDTO.setStaffId(id);
//        EntityWrapper entityWrapper = new EntityWrapper();
        List<StaffVO> staffVOList = staffDao.getStaffVOPage(staffDTO);
        StaffVO staffVO = staffVOList.get(0);
        return staffVO;
    }

    @Override
    public Boolean addStaff(StaffDO staffDO) {
        staffDO.setState(0);//未删除
        staffDO.setStatus(0);//在职状态
        return insert(staffDO);
    }

    @Override
    public Boolean deleteStaff(Integer id) {
        StaffDO staffDO = new StaffDO();
        staffDO.setState(1);
        staffDO.setStaffId(id);
        return updateById(staffDO);
    }

    @Override
    public Boolean updateStatus(Integer id,Integer status) {
        StaffDO staffDO = new StaffDO();
//        if (status.equals(0)){
//            status=1;
//        }else{
//            status = 0;
//        }
        staffDO.setStatus(status);
        staffDO.setStaffId(id);
        return updateById(staffDO);
    }

    @Override
    public HSSFWorkbook exportStaff() {
        String[] title = {"姓名","性别","年龄","入职时间","学历","资质","班组","部门"};
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("员工模板");

//        sheet.addMergedRegion(new CellRangeAddress(0,0,0,8));//第一行第一列开始，跨8列
        HSSFRow titleRow = sheet.createRow(0);//第0行

        //标题样式
        HSSFCellStyle titleStyle = wb.createCellStyle();
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short)18);
        titleStyle.setFont(font);

        //生成标题
        HSSFCell titleCell = titleRow.createCell(0);
        titleCell.setCellValue("员工模板（红色标识列为必填）");
        titleCell.setCellStyle(titleStyle);

        //红色字体
        HSSFCellStyle redStyle = wb.createCellStyle();
        redStyle.setAlignment(HorizontalAlignment.CENTER);
        HSSFFont redFont = wb.createFont();
        redFont.setBold(true);
        redFont.setColor(Font.COLOR_RED);
        redStyle.setFont(redFont);

        //默认字体样式
        HSSFCellStyle defaultStyle = wb.createCellStyle();
        defaultStyle.setAlignment(HorizontalAlignment.CENTER);
        HSSFFont defaultFont = wb.createFont();
        defaultFont.setBold(true);
        defaultStyle.setFont(defaultFont);

        //声明列对象
        HSSFCell cell = null;
        //创建表头
        HSSFRow headRow = sheet.createRow(1);
        for(int i=0;i<title.length;i++){
            //下标为4时时备注，备注选填，字体黑色
//            if (i == 4){
//                cell = headRow.createCell(i);
//                cell.setCellValue(title[i]);
//                cell.setCellStyle(defaultStyle);
//            }else{
                cell = headRow.createCell(i);
                cell.setCellValue(title[i]);
                cell.setCellStyle(redStyle);
//            }
        }

        String[] sexArr = {"男","女"};

        //设置班组为下拉框选项
        DVConstraint sexConstraint = DVConstraint.createExplicitListConstraint(sexArr);
        // 设置数据有效性加载在哪个单元格上,四个参数分别是：起始行、终止行、起始列、终止列
        CellRangeAddressList sexRegions = new CellRangeAddressList(2,
                10000, 1, 1);
        HSSFDataValidation sexData = new HSSFDataValidation(
                sexRegions, sexConstraint);
        sheet.addValidationData(sexData);

        List<MarshallingDO> marshallingDOS = marshallingService.getMarshallingList();
        List<String> marshallingList = marshallingDOS.stream().map(item -> item.getMarshallingName()).collect(Collectors.toList());
        String[] marshallingNameArr = marshallingList.toArray(new String[marshallingList.size()]);

        //设置班组为下拉框选项
        DVConstraint marshallingConstraint = DVConstraint.createExplicitListConstraint(marshallingNameArr);
        // 设置数据有效性加载在哪个单元格上,四个参数分别是：起始行、终止行、起始列、终止列
        CellRangeAddressList marshallingRegions = new CellRangeAddressList(2,
                10000, 6, 6);
        HSSFDataValidation marshallingData = new HSSFDataValidation(
                marshallingRegions, marshallingConstraint);
        sheet.addValidationData(marshallingData);


        List<DeptDO> deptDOS = deptService.getDeptList();
        List<String> deptList = deptDOS.stream().map(item -> item.getName()).collect(Collectors.toList());
        String[] deptNameArr = deptList.toArray(new String[deptList.size()]);

        //设置部门下拉框选项
        DVConstraint deptConstraint = DVConstraint.createExplicitListConstraint(deptNameArr);
        // 设置数据有效性加载在哪个单元格上,四个参数分别是：起始行、终止行、起始列、终止列
        CellRangeAddressList deptRegions = new CellRangeAddressList(2,
                10000, 7, 7);
        HSSFDataValidation deptData = new HSSFDataValidation(
                deptRegions, deptConstraint);
        sheet.addValidationData(deptData);
        return wb;
    }

    @Override
    public void importStaff(MultipartFile file, Long userId) {
        Boolean flag = CellUtil.isExcel(file.getOriginalFilename());
        if (!flag){
            throw new MessageException("只支持Excel文件");
        }

        List<MarshallingDO> marshallingDOS = marshallingService.getMarshallingList();
        List<DeptDO> deptDOS = deptService.getDeptList();

        try {
            HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
            Sheet sheet = wb.getSheetAt(0);
            int rowNum = sheet.getLastRowNum(); //返回行数下标 从0开始
            //前两行都不是内容，所以从2开始
            for (int i = 2; i <= rowNum; i++) {
                Row row = sheet.getRow(i);
                short num = row.getLastCellNum();

                StaffDO staffDO = new StaffDO();
                staffDO.setCreateDate(new Date());
                staffDO.setCreateBy(userId);
                staffDO.setState(0);
                staffDO.setStatus(0);

                Cell staffNameCell = row.getCell(0);
                if (CellUtil.isCellEmpty(staffNameCell))
                    throw new MessageException("员工名称不能为空");
                staffDO.setStaffName(staffNameCell.getStringCellValue());

                Cell sexCell = row.getCell(1);
                if (CellUtil.isCellEmpty(sexCell)){
                    throw new MessageException("性别不能为空");
                }
                if ("男".equals(sexCell.getStringCellValue())){
                    staffDO.setSex(0);
                }else{
                    staffDO.setSex(1);
                }

                Cell ageCell = row.getCell(2);
                if (CellUtil.isCellEmpty(ageCell)){
                    throw  new MessageException("年龄不能为空");
                }
                staffDO.setAge(Integer.parseInt(ageCell.getStringCellValue()));

                Cell entryDateCell = row.getCell(3);
                if (entryDateCell == null || entryDateCell.getDateCellValue() == null){
                    throw new MessageException("入职时间不能为空");
                }
                staffDO.setEntryDate(entryDateCell.getDateCellValue());

                Cell educationCell = row.getCell(4);
                if (CellUtil.isCellEmpty(educationCell)){
                    throw new MessageException("学历不能为空");
                }
                staffDO.setEducation(educationCell.getStringCellValue());

                Cell seniorityCell = row.getCell(5);
                if (CellUtil.isCellEmpty(seniorityCell)){
                    throw new MessageException("资质不能为空");
                }
                staffDO.setSeniority(seniorityCell.getStringCellValue());

                Cell marshallingCell = row.getCell(6);
                if (CellUtil.isCellEmpty(marshallingCell)){
                    throw new MessageException("班组不能为空");
                }
                List<MarshallingDO> marshallingResultList = marshallingDOS.stream().
                        filter(item -> item.getMarshallingName().equals(marshallingCell.getStringCellValue()))
                        .collect(Collectors.toList());
                staffDO.setMarshalling(marshallingResultList.get(0).getMarshallingId());

                Cell deptCell = row.getCell(7);
                if (CellUtil.isCellEmpty(marshallingCell)){
                    throw new MessageException("部门不能为空");
                }
                List<DeptDO> deptResultList = deptDOS.stream().
                        filter(item -> item.getName().equals(deptCell.getStringCellValue()))
                        .collect(Collectors.toList());
                staffDO.setDeptId(deptResultList.get(0).getId());
                insert(staffDO);
            }
//            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
